package com.kanshu.ksgb.fastread.doudou.common.net.retrofit

import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.Xutils
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import com.kanshu.ksgb.fastread.doudou.common.util.MD5Util
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import java.util.*

/**
 * 向所有的get post(表单)网络请求添加通用参数。
 * 如果已经有的基础参数不会再次添加避免覆盖，重复
 */
class CommonRequestParamsInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.method() == "GET") {

            val url = request.url()
            val map = baseRequestParams()
            //移除已有的参数
            for (i in 0 until url.querySize()) {
                map.remove(url.queryParameterName(i))
            }
            //添加不足的通用参数
            val urlBuilder = url.newBuilder()
            map.forEach {entry->
                urlBuilder.addQueryParameter(entry.key, entry.value)
            }
            //构造新的请求
            request = request.newBuilder().url(urlBuilder.build()).build()

        } else if (request.method() == "POST") {
            val body = request.body()
            if (body == null || body is FormBody || body.contentLength() == 0L) {

                val map = baseRequestParams()
                val formBody = FormBody.Builder()

                if (body is FormBody) {
                    for (i in 0 until body.size()) {
                        val name = body.name(i)
                        //将通用参数 已有的参数移除
                        map.remove(name)
                        //添加原有的参数
                        formBody.add(name, body.value(i))
                    }
                }

                //添加通用参数
                map.forEach {entry ->
                    formBody.add(entry.key,entry.value)
                }

                request = request.newBuilder().post(formBody.build()).build()
            }
        }
        return chain.proceed(request)
    }
    private fun baseRequestParams(): MutableMap<String, String> {
        val map = HashMap<String, String>(16)
        map["device_id"] = UserUtils.getDeviceId()
        map["req_time"] = System.currentTimeMillis().toString() + "" + (Random().nextInt(8999) + 1000)
        map["app_key"] = Xutils.getContext().resources.getString(R.string.app_key)
        map["app_token"] = MD5Util.md5(map["device_id"] + "#" + map["req_time"] + "#" + Xutils.getContext().resources.getString(R.string.app_secret))
        map["user_id"] = UserUtils.getUserId()
        map["app_id"] = Xutils.getContext().getString(R.string.app_id)
        map["version"] = Xutils.getContext().getString(R.string.version)
        map["site"] = MMKVUserManager.getInstance().loginSex
        map["registration_id"] = UserUtils.getJpushRegistrationId()
        map["channel_id"] = UserUtils.getChannelId()
        map["is_free_version"] = MMKVDefaultManager.getInstance().isFreeVersion.toString()
        map["__flush_cache"] = if (MMKVDefaultManager.getInstance().isClearCache) "1" else "0"
        map["version_name"] = Utils.getVersionName(Xutils.getContext())
        map["islogin"] = if (MMKVUserManager.getInstance().isUserLogin) "1" else "0"
        return map
    }
}